package com.example.selfservicestation.extensions

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.PackageManager
import android.os.Build
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.util.TypedValue
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.example.selfservicestation.util.Executor
import com.example.selfservicestation.util.NetManager
import java.util.*


fun Context.isAlive() : Boolean {
    return this is Activity && !this.isDestroyed
            || this is ContextWrapper && this.baseContext != null && this.baseContext is Activity
            && !(this.baseContext as Activity).isDestroyed
}


    /**
     * 获取设备序列号
     */
    @Suppress("DEPRECATION")
    @SuppressLint("HardwareIds")
    fun Context.serialNo() : String {
//        return "10000" // 测试
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
            == PackageManager.PERMISSION_GRANTED) {
            return Build.getSerial().uppercase(Locale.ROOT)
        }
        return Build.SERIAL.uppercase(Locale.ROOT)
    }

    /**
     * 检查权限
     */
    fun Context.checkPermissions(permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    /**
     * 网络管理器
     */
    fun Context.netManager() = NetManager.getInstance(applicationContext)

    fun Context.addNetObserver(observer: Observer<Boolean>) {
        netManager().liveData.observeForever(observer)
    }

    fun Context.addNetObserver(owner: LifecycleOwner, observer: (Boolean) -> Unit) {
        netManager().liveData.observe(owner, observer)
    }

    fun Context.removeNetObserver(observer: Observer<Boolean>) {
        netManager().liveData.removeObserver(observer)
    }

    /**
     * 当前网络是否可用
     */
    fun Context.isNetworkAvailbale() : Boolean {
        return netManager().isAvailable()
    }

    fun Context.runOnMainIfNetworkAvailbale(run: () -> Unit) {
        Executor.runOnIO {
            if (isNetworkAvailbale()) {
                Executor.runOnMain { run() }
            }
        }
    }

    fun Context.runIfNetworkAvailbale(run: () -> Unit) {
        Executor.runOnIO {
            if (isNetworkAvailbale()) {
                run()
            }
        }
    }

fun Context.toPx(dp: Int): Float = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    dp.toFloat(),
    resources.displayMetrics)